﻿#include "as_pipe.h"

#ifdef _WIN32
#include <windows.h>
#else
#include <sys/eventfd.h>
#include <unistd.h>
#endif

int Pipe::create_pipe(PIPES &pipe)
{
#ifdef _WIN32
	SECURITY_ATTRIBUTES sa;
	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = TRUE;
	if (!CreatePipe(&pipe[0], &pipe[1], &sa, 0)) {
		return 1;
	}
#else
	pipe[0] = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);

#endif

	return 0;
}

int Pipe::write_pipe(std::array<PIPE_HANDLE, 2> &pipe, std::string_view &buf)
{
#ifdef _WIN32
	DWORD writeLen = 0;
	if (WriteFile(pipe[1], buf.data(), (DWORD)buf.size(), &writeLen, nullptr) == false)
		return -1;
#else
	int writeLen = 0;
	writeLen = ::write(pipe[1], buf.data(), buf.size());
#endif
	return writeLen;
}

int Pipe::read_pipe(std::array<PIPE_HANDLE, 2> &pipe, char *buf, int size)
{
#ifdef _WIN32
	DWORD readLen = 0;
	if (ReadFile(pipe[1], buf, size, &readLen, nullptr) == false)
		return -1;
#else
	int readLen = 0;
	readLen = ::read(pipe[1], buf, size);
#endif
	return readLen;
}

void Pipe::close_pipe(std::array<PIPE_HANDLE, 2> &pipe)
{
#ifdef _WIN32
	CloseHandle(pipe[0]);
	CloseHandle(pipe[1]);
#else
	::close(pipe[0]);
	::close(pipe[1]);
#endif
}
